<template>
  <div class="app-container">
    <!-- 状态导航栏 -->
    <el-tabs v-model="activeStatus" @tab-click="handleStatusChange">
      <el-tab-pane label="全部" name=""></el-tab-pane>
      <el-tab-pane label="口服剂型" name="1"></el-tab-pane>
      <el-tab-pane label="注射剂型" name="2"></el-tab-pane>
      <el-tab-pane label="外用剂型" name="3"></el-tab-pane>
      <el-tab-pane label="吸入剂型" name="4"></el-tab-pane>
      <el-tab-pane label="专用剂型" name="5"></el-tab-pane>
    </el-tabs>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="主键id" prop="id">
        <el-input v-model="queryParams.id" placeholder="请输入主键id" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="药物编号" prop="number">
        <el-input v-model="queryParams.number" placeholder="请输入药物编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="药物名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入药物名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="剂型" prop="dosageForm">
        <el-select v-model="queryParams.dosageForm" placeholder="请选择剂型，1 口服剂型，2 注射剂型，3 外用剂型，4 吸入剂型，5 专用剂型" clearable>
          <el-option v-for="dict in sys_medication_center" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="类别" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类别，1 抗生素类，2 抗病毒药物，3 抗真菌药物，4 抗肿瘤药物，5 镇痛药物，6 抗抑郁药物"
          clearable>
          <el-option v-for="dict in sys_medication_dosageform" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="库存" prop="stock">
        <el-input v-model="queryParams.stock" placeholder="请输入库存" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="平均单价" prop="price">
        <el-input v-model="queryParams.price" placeholder="请输入平均单价" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="剂量" prop="dosage">
        <el-input v-model="queryParams.dosage" placeholder="请输入剂量" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['medication:medication:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['medication:medication:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['medication:medication:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['medication:medication:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="medicationList" @selection-change="handleSelectionChange"
      @row-dblclick="handleView" v-show="isPatient">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键id" align="center" prop="id" />
      <el-table-column label="药物编号" align="center" prop="number" />
      <el-table-column label="药物名称" align="center" prop="name" />
      <el-table-column label="剂型" align="center" prop="dosageForm">
        <template #default="scope">
          <dict-tag :options="sys_medication_center" :value="scope.row.dosageForm" />
        </template>
      </el-table-column>
      <el-table-column label="类别" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="sys_medication_dosageform" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="库存" align="center" prop="stock" />
      <el-table-column label="平均单价" align="center" prop="price" />
      <el-table-column label="剂量" align="center" prop="dosage" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="View" @click="handleView(scope.row)"
            v-hasPermi="['medication:medication:query']">查看</el-button> -->
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['medication:medication:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['medication:medication:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-table v-loading="loading" :data="medicationList" @selection-change="handleSelectionChange" v-show="!isPatient">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键id" align="center" prop="id" />
      <el-table-column label="药物编号" align="center" prop="number" />
      <el-table-column label="药物名称" align="center" prop="name" />
      <el-table-column label="剂型" align="center" prop="dosageForm">
        <template #default="scope">
          <dict-tag :options="sys_medication_center" :value="scope.row.dosageForm" />
        </template>
      </el-table-column>
      <el-table-column label="类别" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="sys_medication_dosageform" :value="scope.row.type" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="库存" align="center" prop="stock" /> -->
      <el-table-column label="平均单价" align="center" prop="price" />
      <el-table-column label="剂量" align="center" prop="dosage" width="300px" />
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)"
            v-hasPermi="['medication:medication:query']">查看</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['medication:medication:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['medication:medication:remove']">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改药物对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="medicationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="药物编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入药物编号" />
        </el-form-item>
        <el-form-item label="药物名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入药物名称" />
        </el-form-item>
        <el-form-item label="剂型" prop="dosageForm">
          <el-select v-model="form.dosageForm" placeholder="请选择剂型，1 口服剂型，2 注射剂型，3 外用剂型，4 吸入剂型，5 专用剂型">
            <el-option v-for="dict in sys_medication_center" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类别" prop="type">
          <el-select v-model="form.type" placeholder="请选择类别，1 抗生素类，2 抗病毒药物，3 抗真菌药物，4 抗肿瘤药物，5 镇痛药物，6 抗抑郁药物">
            <el-option v-for="dict in sys_medication_dosageform" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存" />
        </el-form-item>
        <el-form-item label="平均单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入平均单价" />
        </el-form-item>
        <el-form-item label="剂量" prop="dosage">
          <el-input v-model="form.dosage" placeholder="请输入剂量" />
        </el-form-item>
        <el-divider content-position="center">药物库存信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddMedicationStock">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteMedicationStock">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="medicationStockList" :row-class-name="rowMedicationStockIndex"
          @selection-change="handleMedicationStockSelectionChange" ref="medicationStock">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="供应商id" prop="supplierId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.supplierId" placeholder="请输入供应商id" />
            </template>
          </el-table-column>
          <el-table-column label="生产日期" prop="createDate" width="240">
            <template #default="scope">
              <el-date-picker clearable v-model="scope.row.createDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择生产日期">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="药物有效期" prop="expirationDate" width="240">
            <template #default="scope">
              <el-date-picker clearable v-model="scope.row.expirationDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择药物有效期">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="当前库存数量" prop="quantity" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.quantity" placeholder="请输入当前库存数量" />
            </template>
          </el-table-column>
          <el-table-column label="供应单价" prop="price" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.price" placeholder="请输入供应单价" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看药物详细对话框 -->
    <el-dialog title="药物详细信息" v-model="viewOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="主键id">{{
          viewForm.id
          }}</el-descriptions-item>
        <el-descriptions-item label="药品名称">{{
          viewForm.name
          }}</el-descriptions-item>
        <el-descriptions-item label="药品编号">{{
          viewForm.number
          }}</el-descriptions-item>
        <el-descriptions-item label="类别">
          <dict-tag :options="sys_medication_center" :value="viewForm.type" />
        </el-descriptions-item>
        <el-descriptions-item label="剂型">
          <dict-tag :options="sys_medication_dosageform" :value="viewForm.dosageForm" />
        </el-descriptions-item>
        <el-descriptions-item label="剂量">{{
          viewForm.dosage
          }}</el-descriptions-item>
        <el-descriptions-item label="药品单价">{{
          viewForm.price
          }}</el-descriptions-item>
        <el-descriptions-item label="药品库存">{{
          viewForm.stock
          }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="center">库存明细信息</el-divider>
      <el-table :data="viewForm.medicationStockList">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="药品id" prop="medicationId" align="center" />
        <el-table-column label="供应商id" prop="supplierId" align="center" />
        <el-table-column label="生产日期" prop="createDate" align="center" />
        <el-table-column label="药物有效期" prop="expirationDate" align="center" />
        <el-table-column label="当前库存数量" prop="quantity" align="center" />
        <el-table-column label="供应单价" prop="price" align="center" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Medication">
import {
  listMedication,
  getMedication,
  delMedication,
  addMedication,
  updateMedication,
} from "@/api/medication/medication";
import { getInfo } from "@/api/login";

const { proxy } = getCurrentInstance();
const { sys_medication_center, sys_medication_dosageform } = proxy.useDict(
  "sys_medication_center",
  "sys_medication_dosageform"
);

const medicationList = ref([]);
const medicationStockList = ref([]);
const open = ref(false);
const viewOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedMedicationStock = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const activeStatus = ref("");
const viewForm = ref({});
const isPatient = ref();

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    number: null,
    name: null,
    dosageForm: null,
    type: null,
    stock: null,
    price: null,
    dosage: null,
  },
  rules: {
    number: [{ required: true, message: "药物编号不能为空", trigger: "blur" }],
    name: [{ required: true, message: "药物名称不能为空", trigger: "blur" }],
    dosageForm: [
      {
        required: true,
        message:
          "剂型，1 口服剂型，2 注射剂型，3 外用剂型，4 吸入剂型，5 专用剂型不能为空",
        trigger: "change",
      },
    ],
    type: [
      {
        required: true,
        message:
          "类别，1 抗生素类，2 抗病毒药物，3 抗真菌药物，4 抗肿瘤药物，5 镇痛药物，6 抗抑郁药物不能为空",
        trigger: "change",
      },
    ],
    stock: [{ required: true, message: "库存不能为空", trigger: "blur" }],
    price: [{ required: true, message: "平均单价不能为空", trigger: "blur" }],
    dosage: [{ required: true, message: "剂量不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 状态切换 */
function handleStatusChange(tab) {
  queryParams.value.dosageForm = tab.props.name;
  queryParams.value.pageNum = 1;
  getList();
}

/** 查询药物列表 */
function getList() {
  loading.value = true;
  listMedication(queryParams.value).then((response) => {
    medicationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    number: null,
    name: null,
    dosageForm: null,
    type: null,
    stock: null,
    price: null,
    dosage: null,
  };
  medicationStockList.value = [];
  proxy.resetForm("medicationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加药物";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getMedication(_id).then((response) => {
    form.value = response.data;
    medicationStockList.value = response.data.medicationStockList;
    open.value = true;
    title.value = "修改药物";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["medicationRef"].validate((valid) => {
    if (valid) {
      form.value.medicationStockList = medicationStockList.value;
      if (form.value.id != null) {
        updateMedication(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMedication(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除药物编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delMedication(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 药物库存序号 */
function rowMedicationStockIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 药物库存添加按钮操作 */
function handleAddMedicationStock() {
  let obj = {};
  obj.supplierId = "";
  obj.createDate = "";
  obj.expirationDate = "";
  obj.quantity = "";
  obj.price = "";
  medicationStockList.value.push(obj);
}

/** 药物库存删除按钮操作 */
function handleDeleteMedicationStock() {
  if (checkedMedicationStock.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的药物库存数据");
  } else {
    const medicationStocks = medicationStockList.value;
    const checkedMedicationStocks = checkedMedicationStock.value;
    medicationStockList.value = medicationStocks.filter(function (item) {
      return checkedMedicationStocks.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handleMedicationStockSelectionChange(selection) {
  checkedMedicationStock.value = selection.map((item) => item.index);
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "medication/medication/export",
    {
      ...queryParams.value,
    },
    `medication_${new Date().getTime()}.xlsx`
  );
}

/** 查看按钮操作 */
function handleView(row) {
  getMedication(row.id).then((response) => {
    viewForm.value = response.data;
    viewOpen.value = true;
  });
}

// 获取当前用户角色
function getCurrentUserRole() {
  getInfo().then(response => {
    const roles = response.roles;
    if (roles[0] === 'patient') {
      isPatient.value = false;
    }
    else {
      isPatient.value = true;
    }
    // isPatient.value = roles.some(role => role.roleKey === 'patient');
  });
}

getCurrentUserRole();
getList();
</script>

<style scoped>
.el-descriptions {
  margin-bottom: 20px;
}
</style>
